home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: Functions as parameters
- Date: Wed, 21 Feb 96 23:50:39 GMT
- Organization: none
- Message-ID: <824946639snz@genesis.demon.co.uk>
- References: <Dn4x09.8Hx@undergrad.math.uwaterloo.ca>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <Dn4x09.8Hx@undergrad.math.uwaterloo.ca>
- clgonsal@undergrad.math.uwaterloo.ca
- "Carl Laurence Gonsalves" writes:
-
- >
- >I've often seen and even written code that uses function pointers like
- >this:
- >
- >
- >/* cut here */
- >#include <stdio.h>
- >
- >void foo( int (*func)( int ) ){
- > printf("%d\n", func( 5 ) );
- >}
- >
- >int bar( int x ){
- > return x*2;
- >}
- >
- >int
- >main(){
- > foo( bar );
- > return 0;
- >}
- >/* cut here */
- >
- >Recently though, I saw a similar piece of code that did something like
- >this:
- >
- >/* cut here */
- >void foo( int func( int ) ){
- > printf("%d\n", func( 5 ) );
- >}
- >/* cut here */
- >
- >I tried compiling this with both Watcom C 10.0 and GNU C 2.6.3, and it
- >worked. So my question is: is this standard, or is this some weird compiler
- >extension.
-
- It is standard.
-
- >I've never seen this syntax before. Does it mean the same thing
- >as the first piece of code?
-
- Yes. This is one half of what is known as the rewrite rule for function
- parameters. In the standard (section 6.7.1) it says:
-
- "A declaration of a parameter as ``array of type'' shall be ajusted to
- ``pointer to type'', and a declaration of a paremeter as ``function
- returning type'' shall be adjusted to ``pointer to function returning type'' "
-
- So the compiler treats:
-
- void bar(int a[], void b(void)) {}
-
- as if it were written as:
-
- void bar(int *a, void (*b)(void)) {}
-
- >If they are identical, why is the (*func)(int) syntax so much more common?
-
- 1. It was the only way to do it in most pre-ANSI compilers so it is slightly
- more portable. Also, old habits die hard.
-
- 2. It makes it clear to the reader that a function pointer is being used
- rather than a direct function call.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-